﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using Kevin.Shop.Business.Core.Components.Cookie;
using Kevin.Shop.Business.Core.Components.Responser;
using Kevin.Shop.Business.Core.Member;
using Kevin.Shop.Business.Service.Entity.Helper;
using RiderShop.Mobile.Common.ThirdEntity;
using System.Web.Script.Serialization;
using RiderShop.Mobile.Common.Helper;

namespace RiderShop.Mobile.Common.Component.OAuth.Weixing
{
    public class WeixingOAuth
    {
        public static WeixingOAuthResult OAuth()
        {
            if (!string.IsNullOrEmpty(WebClientContext.Current.OpenId) && LoginByThirdId(WebClientContext.Current.OpenId))
            {
                return new WeixingOAuthResult(true);
            }

            string authorizationUrl = ConfigurationManager.AppSettings["WeixingOAuthUrl"];
            //authorizationUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx29f34de744e0c7c5&amp;redirect_uri={0}&amp;response_type=code&amp;scope=snsapi_userinfo&amp;state=3#wechat_redirect";
            //authorizationUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd6ba880532a24a07&amp;redirect_uri=http://rongji.pupuxing.net&amp;response_type=code&amp;scope=snsapi_userinfo&amp;state=3#wechat_redirect";
            authorizationUrl = string.Format(authorizationUrl, System.Web.HttpUtility.UrlEncode(HttpContext.Current.Request.Url.AbsoluteUri));
            var weixingSwitch = false;
            bool.TryParse(ConfigurationManager.AppSettings["WeixingAuthSwitch"], out weixingSwitch);

            //如果用户没有登录过
            if (weixingSwitch)//&& !WebClientContext.Current.IsAuthenticated)
            {
                //只有第一次进到首页需要重定向到用户授权页面，当微信用户点击'授权'就不会再重定向用户授权页面
                if (HttpContext.Current.Request.QueryString["code"] == null)
                {
                    HttpContext.Current.Response.Redirect(authorizationUrl);
                    //HttpContext.Current.Response.End();
                }
                if (HttpContext.Current.Request.QueryString["code"] != null)
                {
                    string code = HttpContext.Current.Request.QueryString["code"];
                    WinXinUserInfo winxinUserInfo = GetWeixinInfo(code);

                    int userId = LoginByThirdIdReturnUserId(winxinUserInfo.openid);
                    if (userId > 0)
                    {
                        UpdateUser(userId, winxinUserInfo);
                        return new WeixingOAuthResult(true, winxinUserInfo);
                    }
                    else
                    {
                        //微信认证成功，但是用户未绑定
                        return new WeixingOAuthResult(false, winxinUserInfo);
                    }






                    /*        用户不存在，需要用户绑定账号或者创建用户绑定。


                    var serviceResponser = new ServiceResponser(false);

                    if (userList.Count == 0 || userList[0].UserId == 0) //创建用户
                    {
                        var user = new UserBasicInfo();
                        user.ThirdUserId = "weixing_" + winxinUserInfo.openid;
                        user.UserName = "weixing_" + winxinUserInfo.openid;
                        user.RealName = winxinUserInfo.nickname;
                        user.Password = "000000";
                        user.Email = "weixing_" + winxinUserInfo.openid + "@qq.com";
                        user.EnableEmail = false;
                        //user.HeadImgUrl = winxinUserInfo.headimgurl;
                        string url = SiteUrl.FormatUrl("Common_CreateOrUpdateUser");
                        serviceResponser = RestfulHelper.Update(url, user);
                    }
                    else
                    {
                        string url = SiteUrl.FormatUrl("Common_GetUserInfo", userList[0].UserId);
                        var user = RestfulHelper.QueryWithSingle<UserBasicInfo>(url);
                        //user.HeadImgUrl = winxinUserInfo.headimgurl ?? string.Empty;
                        url = SiteUrl.FormatUrl("Common_CreateOrUpdateUser");
                        serviceResponser = RestfulHelper.Update(url, user);
                    }
                    if (serviceResponser.Status || userList[0].UserId > 0)
                    {
                        userList = RestfulHelper.Query<UserBasicInfo>(urlGetUser);
                    }
                     
                     */
                }
            }
            return new WeixingOAuthResult();
        }


        public static WinXinUserInfo GetWeixinOAuthInfo()
        {
            string authorizationUrl = ConfigurationManager.AppSettings["WeixingOAuthUrl"];
            authorizationUrl = string.Format(authorizationUrl, System.Web.HttpUtility.UrlEncode(HttpContext.Current.Request.Url.AbsoluteUri));
            var weixingSwitch = false;
            bool.TryParse(ConfigurationManager.AppSettings["WeixingAuthSwitch"], out weixingSwitch);

            if (weixingSwitch)
            {
                //只有第一次进到首页需要重定向到用户授权页面，当微信用户点击'授权'就不会再重定向用户授权页面
                if (HttpContext.Current.Request.QueryString["code"] == null)
                {
                    HttpContext.Current.Response.Redirect(authorizationUrl);
                    //HttpContext.Current.Response.End();
                }
                if (HttpContext.Current.Request.QueryString["code"] != null)
                {
                    string code = HttpContext.Current.Request.QueryString["code"];
                    WinXinUserInfo winxinUserInfo = GetWeixinInfo(code);
                    return winxinUserInfo;
                }
            }
            return new WinXinUserInfo();

        }

        public static int LoginByThirdIdReturnUserId(string openid)
        {
            var userList = new List<UserBasicInfo>();
            string urlGetUser = SiteUrl.FormatUrl("Common_GetUserInfoByThirdId", "weixing_" + openid);
            if (!string.IsNullOrEmpty(openid))
            {
                userList = RestfulHelper.Query<UserBasicInfo>(urlGetUser);
            }
            //用户信息已经存在于我们的用户表里
            if (userList.Count > 0 && userList[0].UserId > 0)
            {
                WebClientContext.Current.OpenId = openid;
                FormsAuthentication.SetAuthCookie(userList[0].UserName, true);
                WebClientContext.Current.GetCurrentUser(false);

                return userList[0].UserId;
            }

            //微信认证成功，但是用户未绑定
            return 0;
        }

        public static bool LoginByThirdId(string openid)
        {
            var userList = new List<UserBasicInfo>();
            string urlGetUser = SiteUrl.FormatUrl("Common_GetUserInfoByThirdId", "weixing_" + openid);
            if (!string.IsNullOrEmpty(openid))
            {
                userList = RestfulHelper.Query<UserBasicInfo>(urlGetUser);
            }
            //用户信息已经存在于我们的用户表里
            if (userList.Count > 0 && userList[0].UserId > 0)
            {
                WebClientContext.Current.OpenId = openid;
                FormsAuthentication.SetAuthCookie(userList[0].UserName, true);
                WebClientContext.Current.GetCurrentUser(false);

                return true;
            }

            //微信认证成功，但是用户未绑定
            return false;
        }

        public static WinXinUserInfo GetWeixinInfo(string code)
        {



            Access_Token access_token = Utility.GetOauth2_Access_Token(code);

            WinXinUserInfo winxinUserInfo = Utility.GetUserInfo(access_token);
            return winxinUserInfo;
        }

        public static string UsePromotionCode(string code, string cardId)
        {
            string access_token = Utility.GetAccess_Token();

            var urlFormat = string.Format("https://api.weixin.qq.com/card/code/consume?access_token={0}", access_token);

            var data = new
            {
                code = code,
                card_id = cardId
            };

            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            var json = jsonSerializer.Serialize(data);
            Kevin.Comm.Logger.Tracer.TraceLog("USE promotion code address: " + urlFormat, "Use Promotion Code", "PromotionCode", true);
            Kevin.Comm.Logger.Tracer.TraceLog("USE promotion code code: " + code, "Use Promotion Code", "PromotionCode", true);

            var response = Utility.PostBody(urlFormat, json, Encoding.UTF8);
            Kevin.Comm.Logger.Tracer.TraceLog("USE promotion code: " + response, "Use Promotion Code", "PromotionCode", true);

            return code;
        }

        public static ServiceResponser UpdateUser(int userId, WinXinUserInfo winxinUserInfo)
        {
            ServiceResponser result=new ServiceResponser();
            UserBasicInfo user = CacheUsers.Get(userId, false);
            if (user.HeadImgUrl != winxinUserInfo.headimgurl)
            {
                user.HeadImgUrl = winxinUserInfo.headimgurl;
                result = RestfulHelper.Update<UserBasicInfo>(SiteUrl.FormatUrl("Common_CreateOrUpdateByWebSite"), user);
            }
            return result;

        }
    }


    public class WeixingOAuthResult
    {
        public WeixingOAuthResult()
        { }

        public WeixingOAuthResult(bool status)
        {
            this.Status = status;
        }

        public WeixingOAuthResult(bool status, WinXinUserInfo weixinUserInfo)
        {
            this.Status = status;
            this.WeixinUserInfo = weixinUserInfo;
        }

        public bool Status { get; set; }
        public string Message { get; set; }
        public WinXinUserInfo WeixinUserInfo { get; set; }
    }
}
